const GANTT = 'gantt_data';
const getGantt = () => JSON.parse(localStorage.getItem(GANTT)) || [];
const setGantt = (item) => localStorage.setItem(GANTT, JSON.stringify(item));
const reuslt = (item, options ={ msg: '操作成功', code: 200 }) => {
  return new Promise((resolve, reject) => {
    resolve({
      status: 200,
      data: {
        data: item,
        ...options
      },
    });
  });
};
// api
export const getGanttData = (id) => {
  let data = [];
  // 查询所有
  if (!id) data = getGantt().filter(item => item.grade === 0);
  else {
    data = getGantt().filter(item => item.id == id || item.rootId == id);
    data = merge(data);
  }
  return reuslt(data);
}; 
export const addGanttData = (item) => reuslt(setGantt([...getGantt(), item]));
export const editGanttData = (data) => {
  // 找到所有数据
  let tag = getGantt().findIndex(item => data.rootId === item.id);
  // console.log(real, total);
  // 修改进度
  let list = getGantt();
  const index = list.findIndex(item => item.id === data.id);
  list[index].actual_process = data.actual_process;
  list[tag].actual_process = parseFloat(Math.random().toFixed(2));
  return reuslt(setGantt(list));
}

// 数据合并
function merge(data) {
 // 按层级降序排序
 data = data.sort((a, b) => b.grade - a.grade);
 let i = 0;
 while (data.length !== 1) {
  if (i >= data.length) i = 0;
  if (data[0].parentId === data[i].id) {
    data[i].children.push(data[0]);
    data.splice(0, 1);
    i = 0;
  }
  i++;
 }
 return data;
}
